package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public Result<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        // 设置用户id， 指定当前是哪个用户的购物车
        Long currentId = BaseContext.getCurrent();
        shoppingCart.setUserId(currentId);
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, currentId);

        // 查询当前菜品是否在购物车已经存在
        if (shoppingCart.getDishId() != null) {
            // 添加到购物车的是 菜品
            lambdaQueryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());

        } else {
            // 否则是套餐
            lambdaQueryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart shoppingCartOne = shoppingCartService.getOne(lambdaQueryWrapper);


        // 如果已存在，则原来基础上 +1
        if (shoppingCartOne != null) {
            int i = shoppingCartOne.getNumber() + 1;
            shoppingCartOne.setNumber(i);
            shoppingCartService.updateById(shoppingCartOne);
        } else {
            // 如果不存在，则添加到购物车，数量默认1
            shoppingCart.setNumber(1);
            shoppingCartOne.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            shoppingCartOne = shoppingCart;
        }

        return Result.success(shoppingCartOne);
    }

    @GetMapping("/list")
    public Result<List<ShoppingCart>> list() {
        Long current = BaseContext.getCurrent();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, current);
        lambdaQueryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(lambdaQueryWrapper);
        return Result.success(list);
    }

    @DeleteMapping("/clean")
    public Result<String> clean() {
        Long current = BaseContext.getCurrent();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, current);
        shoppingCartService.remove(lambdaQueryWrapper);
        return Result.success("清空购物车成功");
    }
}
